using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebSvrUpdaterCore.Models;
using WebUpdaterAdminCore.Data;
using WebUpdaterAdminCore.Models;
using WebUpdaterAdminCore.Utils;

namespace WebUpdaterAdminCore.WebApi
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class AppPoolController : Controller
    {
        private ApplicationDbContext _dbContext;
        private UpdaterSocketServerService _socketServerService;

        public AppPoolController(ApplicationDbContext dbContext,
            UpdaterSocketServerService updaterSocket)
        {
            _dbContext = dbContext;
            _socketServerService = updaterSocket;
        }

        /// <summary>
        /// 查询客户端程序池
        /// </summary>
        /// <param name="id">客户端ID</param>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<IActionResult> Query(string id)
        {

            var session = _socketServerService.GetSessionByID(id);
            if (session != null)
            {
                var uid = await session.SendAppPoolInfoAsync(_dbContext, HttpContext.User.Identity.Name ?? "Test", new AppPoolInfoRequest { AppPoolName = "#ALL_POOL#" });
                //return Json(new OKResult<string>(uid));

                if (string.IsNullOrEmpty(uid))
                {
                    return Json(new ErrorResult(100101, "发送请求失败"));
                }
                else
                {
                    var msg = await SocketResponeHelper.GetRespone(uid);

                    if (msg != null)
                    {
                        var respone = msg.ReceiveData as AppPoolInfoRespone;
                        if (respone != null)
                        {
                            var poolNames = respone.AppPoolModels.Select(m => { return m.Name; }).ToArray();
                            msg.ReceiveData = poolNames;
                        }
                        return Json(new OKResult<MsgReceiveModel>(msg));
                    }
                    else
                    {
                        return Json(new ErrorResult(100102, "请求尚未完成或者请求不存在"));
                    }

                }
            }        
            else
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
        }
        
        [HttpGet("[action]")]
        public async Task<IActionResult> Result(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "请求参数不能为空"));
            }
            else
            {
                var msg = UpdaterSocketServerService.GetReceiveMsg(id);
                for(int i = 0; i < 10; i++)
                {
                    if (msg == null)
                    {
                        await Task.Delay(20*i);
                        msg = UpdaterSocketServerService.GetReceiveMsg(id);
                    }
                    else
                    {
                        break;
                    }
                }
                
                if (msg != null)
                {
                    var respone = msg.ReceiveData as AppPoolInfoRespone;
                    if (respone != null)
                    {
                        var poolNames = respone.AppPoolModels.Select(m => { return m.Name; }).ToArray();
                        msg.ReceiveData = poolNames;
                    }
                    return Json(new OKResult<MsgReceiveModel>(msg));
                }
                else
                {
                    return Json(new ErrorResult(100102, "请求尚未完成或者请求不存在"));
                }

            }
        }
    }
}
